package com.happok.onlineclass.usermanagement.authentication.config.handler;

import cn.hutool.json.JSONObject;
import com.happok.onlineclass.usermanagement.authentication.config.exception.ValidateCodeException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * [简要描述]:
 * [详细描述]:
 *
 * @author:
 * @date: 5:44 PM 2019/10/17
 * @since: JDK 1.8
 */
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        JSONObject jsonObject = new JSONObject(true);
        if (exception instanceof ValidateCodeException){
            response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
            jsonObject.set("code", exception.getMessage().split("@")[0]);
            jsonObject.set("msg", exception.getMessage().split("@")[1]);
        }else if (exception instanceof UsernameNotFoundException) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            jsonObject.set("code", "40103");
            jsonObject.set("msg", "用户名或密码错误");
        } else if (exception instanceof DisabledException) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            jsonObject.set("code", "40104");
            jsonObject.set("msg", "账户被禁用");
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            jsonObject.set("code", "40105");
            jsonObject.set("msg", "登录失败!");
        }
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(jsonObject.toString());
        response.flushBuffer();
    }
}
